#!/usr/bin/env bash
#
# Summary: Display the full path to an executable
#
# Usage: goenv which <command>
#
# Displays the full path to the executable that goenv will invoke when
# you run the given command.

set -e
[ -n "$GOENV_DEBUG" ] && set -x

# Provide goenv completions
if [ "$1" = "--complete" ]; then
  exec goenv-shims --short
fi

GOENV_COMMAND="$1"

if [ -z "$GOENV_COMMAND" ]; then
  goenv-help --usage which >&2
  exit 1
fi

OLDIFS="$IFS"
IFS=: versions=(${GOENV_VERSION:-$(goenv-version-name)})
IFS="$OLDIFS"

remove_from_path() {
  local path_to_remove="$1"
  local path_before
  local result=":$PATH:"
  while [ "$path_before" != "$result" ]; do
    path_before="$result"
    result="${result//:$path_to_remove:/:}"
  done
  result="${result%:}"
  echo "${result#:}"
}

for version in "${versions[@]}"; do
  if [ "$version" = "system" ]; then
    PATH="$(remove_from_path "${GOENV_ROOT}/shims")"
    GOENV_COMMAND_PATH="$(command -v "$GOENV_COMMAND" || true)"
  else
    GOENV_COMMAND_PATH="${GOENV_ROOT}/versions/${version}/bin/${GOENV_COMMAND}"
  fi
  if [ -x "$GOENV_COMMAND_PATH" ]; then
    break
  elif [[ "$version" != "system" && "${GOENV_DISABLE_GOPATH}" != "1" ]]; then
    if [ -n "${GOENV_GOPATH_PREFIX}" ]; then
      GOENV_COMMAND_PATH="${GOENV_GOPATH_PREFIX}/${version}/bin/${GOENV_COMMAND}"
    else
      GOENV_COMMAND_PATH="${HOME}/go/${version}/bin/${GOENV_COMMAND}"
    fi
    if [ -x "$GOENV_COMMAND_PATH" ]; then
      break
    fi
  fi
done

version_exists() {
  local input_version="$1"
  local use_go_mod="$2"

  if [[ -n use_go_mod ]] && [[ -d ${GOENV_ROOT}/versions ]] && grep -q -E "^[0-9]+\.[0-9]+(\s*)$" <<<${input_version}; then
    OLDIFS="$IFS"
    IFS=$'\n'
    local version_regex=$(echo ${input_version} | sed s/\\./\\\\./)
    local versions=($(/bin/ls ${GOENV_ROOT}/versions | grep -E "^$version_regex(\\.[0-9]+)?$" | sort -V))
    IFS="$OLDIFS"
    if [[ ${#versions[@]} -eq 0 ]]; then
      return 1
    fi
    version=${versions[${#versions[@]} - 1]}
  fi

  [ -d "${GOENV_ROOT}/versions/${version}" ]
}

OLDIFS="$IFS"
IFS=$'\n'
scripts=($(goenv-hooks which))
IFS="$OLDIFS"
for script in "${scripts[@]}"; do
  source "$script"
done

if [ -x "$GOENV_COMMAND_PATH" ]; then
  echo "$GOENV_COMMAND_PATH"
  exit 0
fi

any_not_installed=0
for version in "${versions[@]}"; do
  if [ "$version" = "system" ]; then
    continue
  fi
  if ! version_exists "$version" "$GOENV_GO_MOD_ENABLE"; then
    echo "goenv: version '$version' is not installed (set by $(goenv-version-origin))" >&2
    any_not_installed=1
  fi
done
if [ "$any_not_installed" = 1 ]; then
  exit 1
fi

echo "goenv: '$GOENV_COMMAND' command not found" >&2

versions="$(goenv-whence "$GOENV_COMMAND" || true)"
if [ -n "$versions" ]; then
  {
    echo
    echo "The '$1' command exists in these Go versions:"
    echo "$versions" | sed 's/^/  /g'
    echo
  } >&2
fi

exit 127
